{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 1.3 Dirichlet boundary conditions\n",
    "\n",
    "This tutorial goes in depth into the mechanisms required to solve the Dirichlet problem \n",
    "\n",
    "$$\n",
    "-\\Delta u  = f \\quad \\text{ in } \\Omega, \n",
    "$$\n",
    "\n",
    "with a **nonzero** Dirichlet boundary condition\n",
    "\n",
    "$$\n",
    "u|_{\\Gamma_D} = g\n",
    "\\quad \\text{ on a boundary part }  \\Gamma_D \\subset \\partial\\Omega.\n",
    "$$ \n",
    "\n",
    "The same mechanisms are used in solving boundary value problems involving operators other than the Laplacian.\n",
    "\n",
    "You will see how to perform these tasks in NGSolve:\n",
    "\n",
    "* extend Dirichlet data from boundary parts, \n",
    "\n",
    "* convert boundary data into a volume source,\n",
    "\n",
    "* reduce inhomogeneous Dirichlet case to the homogeneous case, and \n",
    "\n",
    "* perform all these tasks automatically within a utility.\n",
    "\n",
    "If you are just interested in the *automatic utility,* then please skip to the last part of the tutorial. "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Spaces with Dirichlet conditions on part of the boundary"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "('bottom', 'right', 'top', 'left')"
      ]
     },
     "execution_count": 1,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import netgen.gui\n",
    "from ngsolve import *\n",
    "from netgen.geom2d import unit_square\n",
    "\n",
    "mesh = Mesh(unit_square.GenerateMesh(maxh=0.2))\n",
    "mesh.GetBoundaries()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The `unit_square` has its boundaries marked as `left`, `right`, `top` and `bottom`. Suppose we want non-homogeneous Dirichlet boundary conditions on \n",
    "\n",
    "$$\n",
    "\\Gamma_D = \\Gamma_{left} \\cup \\Gamma_{right}.\n",
    "$$\n",
    "\n",
    "Then, we set the space as follows:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "fes = H1(mesh, order=2, dirichlet=\"left|right\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Compare this space with the one without the `dirichlet` flag:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(133, 133)"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "fs2 = H1(mesh, order=2)\n",
    "fes.ndof, fs2.ndof    # total number of unknowns"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Thus, the `dirichlet` flag did not change `ndof`. In NGSolve the unknowns are split into two groups: \n",
    " * dirichlet dofs (or constrained dofs), \n",
    " * free dofs.\n",
    " \n",
    "The facility `FreeDofs` gives a `BitArray` such that `FreeDofs[dof]` is True if and only if `dof` is a free degree of freedom."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "free dofs of fs2 without \"dirichlet\" flag:\n",
      " 0: 11111111111111111111111111111111111111111111111111\n",
      "50: 11111111111111111111111111111111111111111111111111\n",
      "100: 111111111111111111111111111111111\n",
      "free dofs of fes:\n",
      " 0: 00001111000011110000111111111111111111110101011011\n",
      "50: 11111111110110110111111111111111011011011111111111\n",
      "100: 111111111111111111111111111111111\n"
     ]
    }
   ],
   "source": [
    "print(\"free dofs of fs2 without \\\"dirichlet\\\" flag:\\n\",\n",
    "      fs2.FreeDofs())\n",
    "print(\"free dofs of fes:\\n\", fes.FreeDofs())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "* The space `fs2` without `dirichlet` flag has only free dofs (no dirichlet dofs).\n",
    "\n",
    "* The other space `fes` has a few dofs that are marked as *not* free. These are the dofs that are located on the boundary regions we marked as `dirichlet`."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "###  Extension of boundary data  \n",
    "\n",
    "We use the standard technique of reducing a problem with essential non-homogeneous boundary conditions to one with homogeneous boundary condition using an  extension. The solution $u$ in $H^1$ satisfies \n",
    "\n",
    "$$\n",
    "u|_{\\Gamma_D} = g$$\n",
    "\n",
    "and \n",
    "\n",
    "$$ \n",
    "\\int_\\Omega \\nabla u \\cdot \\nabla v_0 = \\int_\\Omega f v_0\n",
    "$$\n",
    "\n",
    "for all $v_0$ in $\\in H_{0,D}^1 = \\{ v \\in H^1: v|_{\\Gamma_D} = 0\\}$. Split the solution \n",
    "\n",
    "$$\n",
    "u = u_0 + u_D\n",
    "$$\n",
    "\n",
    "where $u_D$ is an extension of $g$ into $\\Omega$.   Then we only need to find $u_0$ in $H^1_{0,D}$ satisfying the homogeneous Dirichlet problem \n",
    "\n",
    "$$\n",
    "\\int_\\Omega \\nabla u_0 \\cdot \\nabla v_0 = \\int_\\Omega f v_0 - \\int_\\Omega \\nabla u_D \\cdot \\nabla v_0 \n",
    "$$\n",
    "\n",
    "for all $v_0$ in $H_{0,D}^1$. These are the **issues to consider** in this approach:"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    " * How to define an extension $u_D$ in the finite element space?\n",
    " * How to form and solve the system for $u_0$?\n",
    "\n",
    "Let us address the first in the following example."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Suppose we are given that \n",
    "$$\n",
    "g = \\sin(y) \\qquad \\text{ on } \\; \\Gamma_D.\n",
    "$$"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "g = sin(y)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We interpolate $g$ on the boundary of the domain and extend it to zero  on the elements not having an intersection with $\\Gamma_D$."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "gfu = GridFunction(fes)\n",
    "gfu.Set(g, BND)\n",
    "Draw(gfu)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The keyword `BND` tells `Set` that `g` need only be interpolated on those parts of the boundary that are marked `dirichlet`.\n",
    "\n",
    "Thus, `gfu` now contains the extension $u_D$. Next, we turn to set up the system for $u_0$."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Forms and assembly"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In NGSolve, bilinear and linear forms are defined independently of the dirichlet flags. Matrices and vectors are set up with respect to all unknowns (free or constrained) so they may be restricted to any group of unknowns later."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "u, v = fes.TnT()\n",
    "\n",
    "a = BilinearForm(fes, symmetric=True)\n",
    "a += grad(u)*grad(v)*dx\n",
    "a.Assemble()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "If $A=$ `a.mat` is the matrix just assembled, then we want to solve for \n",
    "\n",
    "$$\n",
    "  A (u_0 + u_D) = f \\quad \\Rightarrow \\quad A u_0 = f - A u_D\n",
    "$$\n",
    "\n",
    "or\n",
    "\n",
    "$$\n",
    "  \\left( \\begin{array}{cc} A_{FF} & A_{FD} \\\\ A_{DF} & A_{DD} \\end{array} \\right) \\left( \\begin{array}{c} u_{0,F} \\\\ 0 \\end{array} \\right) = \\left( \\begin{array}{c} {f}_F \\\\ {f}_D \\end{array} \\right) - \\left( \\begin{array}{cc} A_{FF} & A_{FD} \\\\ A_{DF} & A_{DD} \\end{array} \\right) \\left( \\begin{array}{c} u_{D,F} \\\\ u_{D,D} \\end{array} \\right)\n",
    "$$\n",
    "\n",
    "where we have block partitioned using free dofs ($F$) and dirichlet dofs ($D$) as if they were numbered consecutively (which may not be the case in  practice) for ease of presentation.  The first row gives\n",
    "\n",
    "$$\n",
    "A_{FF} u_{0,F} = f_F - [A u_D]_F.\n",
    "$$\n",
    "\n",
    "Since we have already constructed $u_D$, we need to perform \n",
    "these next steps:\n",
    "\n",
    "- Set up the right hand side from $f$ and $u_D$.\n",
    "- Solve a linear system which involves only $A_{FF}$.\n",
    "- Add solution: $u = u_0 + u_D$."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Solve for the free dofs"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We need to assemble the right hand side of $A_{FF} u_{0,F} = f_F - [A u_D]_F$, namely\n",
    "$$\n",
    "r = f - A u_D.\n",
    "$$"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "f = LinearForm(fes)\n",
    "f += 1*v*dx\n",
    "f.Assemble()\n",
    "\n",
    "r = f.vec.CreateVector()\n",
    "r.data = f.vec - a.mat * gfu.vec"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The implementation of \n",
    "\n",
    "$$\n",
    "u = \n",
    "u_D + \n",
    "\\left( \\begin{array}{cc} A_{FF}^{-1} & 0 \\\\ 0 & 0 \\end{array} \\right) r\n",
    "$$\n",
    "\n",
    "by sparse solvers is achieved by the following:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [],
   "source": [
    "gfu.vec.data += a.mat.Inverse(freedofs=fes.FreeDofs()) * r  \n",
    "Redraw()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### The automatic utility `BVP`\n",
    "\n",
    "NGSolve also provides a `BVP` facility in the `solvers` submodule, within which the above steps are performed automatically. You provide $A$, $f$, a grid function `gfu` with your boundary condition $g$, and a preconditioner. Then `BVP` solves the problem with non-homogeneous Dirichlet boundary condition and overwrites `gfu` with the solution."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "iteration 0 error = 1.314716719533443\n",
      "iteration 1 error = 0.7386137451024543\n",
      "iteration 2 error = 0.7017048185724805\n",
      "iteration 3 error = 0.5798033886499745\n",
      "iteration 4 error = 0.5156226252006282\n",
      "iteration 5 error = 0.27952978178499627\n",
      "iteration 6 error = 0.1994943852477073\n",
      "iteration 7 error = 0.13012477304288342\n",
      "iteration 8 error = 0.06157273289497939\n",
      "iteration 9 error = 0.04132241449978128\n",
      "iteration 10 error = 0.02639327351419442\n",
      "iteration 11 error = 0.017721412824787095\n",
      "iteration 12 error = 0.011789051981713192\n",
      "iteration 13 error = 0.007384221808077659\n",
      "iteration 14 error = 0.004215923531184829\n",
      "iteration 15 error = 0.002154846924422169\n",
      "iteration 16 error = 0.00108651576676954\n",
      "iteration 17 error = 0.0005038044551360859\n",
      "iteration 18 error = 0.00028365353829789045\n",
      "iteration 19 error = 0.00013007722981478649\n",
      "iteration 20 error = 6.301486748019216e-05\n",
      "iteration 21 error = 3.632818204359612e-05\n",
      "iteration 22 error = 2.1145213335816055e-05\n",
      "iteration 23 error = 1.2645843091718868e-05\n",
      "iteration 24 error = 6.104749325035233e-06\n",
      "iteration 25 error = 3.3473256565802637e-06\n",
      "iteration 26 error = 1.7722337788822112e-06\n",
      "iteration 27 error = 1.0406250291945074e-06\n",
      "iteration 28 error = 5.419112194567083e-07\n",
      "iteration 29 error = 2.3778265876140282e-07\n",
      "iteration 30 error = 1.3985263978745102e-07\n",
      "iteration 31 error = 7.691960959166143e-08\n",
      "iteration 32 error = 3.692533181214162e-08\n",
      "iteration 33 error = 1.615566942610009e-08\n",
      "iteration 34 error = 8.050145446797175e-09\n"
     ]
    }
   ],
   "source": [
    "gfu.Set(g, BND)\n",
    "c = Preconditioner(a,\"local\")   #<- Jacobi preconditioner\n",
    "#c = Preconditioner(a,\"direct\") #<- sparse direct solver\n",
    "c.Update()\n",
    "solvers.BVP(bf=a, lf=f, gf=gfu, pre=c)\n",
    "Redraw()"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
